package liumengbaio.lolzhangyoubao.Activity.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import liumengbaio.lolzhangyoubao.Activity.Adapter.AllPlayHottestAdapter;
import liumengbaio.lolzhangyoubao.Activity.InFo.FreeHeroInfo;
import liumengbaio.lolzhangyoubao.Activity.InFo.PlayersPublishInfo;
import liumengbaio.lolzhangyoubao.Activity.View.xListView.XListView;
import liumengbaio.lolzhangyoubao.R;

/**
 * Created by lanouhn on 16/9/10.
 */
public class FragmentAllPlayHottest extends Fragment implements XListView.IXListViewListener{
    private XListView xListViewHottest;
    private AllPlayHottestAdapter allplayHottestAdapter;
    String  id;
    public static FragmentAllPlayHottest newInstants(FreeHeroInfo info) {
        FragmentAllPlayHottest fragmentAllPlayHottest = new FragmentAllPlayHottest();
        Bundle bundle = new Bundle();
        bundle.putSerializable("hottestinfo",info);
        fragmentAllPlayHottest.setArguments(bundle);
        return fragmentAllPlayHottest;
    }

    /**
     * 真正加载到adapter的集合
     */
    private List<PlayersPublishInfo.DataBean> infos = new ArrayList<>();

    /**
     * 中间暂存数据集合
     */
    private List<PlayersPublishInfo.DataBean> temp = new ArrayList<>();

    /**
     * 页码
     */
    private int page = 1;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_allplayhottest,null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView(getView());
        getDatafromWeb();
    }



    private void initView(View view) {
        xListViewHottest= (XListView) view.findViewById(R.id.xListView_hottest);
        xListViewHottest.setPullLoadEnable(true);
        xListViewHottest.setPullRefreshEnable(true);
        xListViewHottest.setXListViewListener(this);
        FreeHeroInfo info = (FreeHeroInfo) getArguments().getSerializable("hottestinfo");
        id=info.getId();
    }
    private void getDatafromWeb() {
        String url ="http://lol.zhangyoubao.com/apis/rest/PlaysService/userPlayList?order_kind=1&role_id="+id+"&season=8&page="+page+"&i_=5Xot/XAKrRDYLof0HC98jNX5%2B4U6gHNT%2BaraufYsX04=&deviceId=5Xot/XAKrRDYLof0HC98jNX5%2B4U6gHNT%2BaraufYsX04=&t_=1473651267278&p_=24179&v_=400902&a_=lol&pkg_=com.anzogame.lol&d_=android&osv_=23&cha=tencentMartket&u_=&modle_=SM-C7000&api=PlaysService.userPlayList&time=1473651266&game=lol&secretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&secretVersion=v1.0&nonce=134254&secretSignature=o20y1xLHEeU6VAkOxLAZLUlGMJs=";
        OkHttpClient client = new OkHttpClient();
        //创建一个Request，传入请求地址
        Request request = new Request.Builder()
                .url(url)
                .build();
        //执行请求并返回一个Call对象
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                //获取请求结果
                String result = response.body().string();
                //解析数据
                Gson gson = new Gson();
                PlayersPublishInfo info = gson.fromJson(result, PlayersPublishInfo.class);

                //判断是否是最后的数据
                //{"data":[],"code":200,"message":"ok","api":1}
                if (info.getCode() == 200 && info.getData().size() == 0) {
                    handler.sendEmptyMessage(2);
                } else {
                    temp = info.getData();
                    if (temp.size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            }
        });
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    xListViewHottest.complete();
                    Toast.makeText(getActivity(), "网络请求失败!", Toast.LENGTH_SHORT).show();
                    break;
                case 1:

                    if (page == 1) {
                        //下拉刷新
                        infos.clear();
                        infos.addAll(temp);
                        allplayHottestAdapter = new AllPlayHottestAdapter(infos,getActivity());
                        xListViewHottest.setAdapter(allplayHottestAdapter);
                        temp.clear();

                        xListViewHottest.setPullLoadEnable(true);
                    } else {
                        //上拉加载
                        infos.addAll(temp);
                        allplayHottestAdapter.notifyDataSetChanged();
                        temp.clear();
                    }

                    xListViewHottest.complete();
                    break;

                case 2:
                    //最后一页
                    xListViewHottest.complete();
                    xListViewHottest.setPullLoadEnable(false);
                    Toast.makeText(getActivity(), " 已经是最后一页啦 !", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    public void onRefresh() {
        //改变请求地址
        page = 1;
        //调用请求方法
        getDatafromWeb();
    }

    @Override
    public void onLoadMore() {

        //改变请求地址
        page++;
        //调用请求方法
        getDatafromWeb();
    }
    }

